package cool.houge.pig.infra.web;

import java.util.List;
import org.springframework.boot.autoconfigure.web.WebProperties.Resources;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * 异常处理器.
 *
 * @author KK (kzou227@qq.com)
 */
@Component
public class MySpringErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

  private final WebErrorHandler webErrorHandler;

  /**
   * @param errorAttributes
   * @param resources
   * @param applicationContext
   * @param jackson2JsonEncoder
   * @param webErrorHandler
   */
  public MySpringErrorWebExceptionHandler(
      ErrorAttributes errorAttributes,
      Resources resources,
      ApplicationContext applicationContext,
      Jackson2JsonEncoder jackson2JsonEncoder,
      WebErrorHandler webErrorHandler) {
    super(errorAttributes, resources, applicationContext);
    super.setMessageWriters(List.of(new EncoderHttpMessageWriter<>(jackson2JsonEncoder)));
    this.webErrorHandler = webErrorHandler;
  }

  @Override
  protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
    return RouterFunctions.route(
        RequestPredicates.all(),
        request -> webErrorHandler.handle(errorAttributes.getError(request), request));
  }
}
